<?php
namespace Api\Controller;

use Common\Util\AttachmentUtil;
use Common\Util\BaseData;
use Qiniu\Auth;
use Services\Upload\UploadService;

class UploadController extends AuthController
{
	const MAX_SIZE = 50 * 1024 * 1024;//上传文件限制50m
    /** @var UploadService $uploadService */
    private $uploadService;
    public function __construct()
    {
        $this->uploadService = new UploadService();
    }

    public function uploadImg()
    {
        $driver = C('PICTURE_UPLOAD_DRIVER');
        $config = [
            'maxSize' => 5 * 1024 * 1024, // 10M 上传的文件大小限制 (0-不做限制)
            'exts' => ['jpg', 'gif', 'png', 'jpeg',], // 允许上传的文件后缀
            'rootPath' => '/Data/upload/images/',
        ];

        if (empty($_FILES['file'])) $this->return_app_data(self::ERROR_CODE, '没有上传文件');
        // 判断附件是否已存在
        $file_md5 = get_file_hash($_FILES['file']['tmp_name'], 'md5');
        if ($file_exists = AttachmentUtil::getAttachmentInfoByMd5($file_md5)) {
            $this->return_app_data(self::SUCCESS_CODE, [
                'path' => $file_exists['path'],
                'url' => $file_exists['path'],
            ]);
        }

        // 实例化上传类
        $upload = new \Think\Upload($config, C('PICTURE_UPLOAD_DRIVER'), C("UPLOAD_{$driver}_CONFIG"));
        // 上传文件
        $info = $upload->uploadOne($_FILES['file']);
        // 上传错误提示错误信息
        if (!$info) $this->return_app_data(self::ERROR_CODE, $upload->getError());
        $file_info = [
            'user_id' => 0,
            'name' => $_FILES['file']['name'],
            'mime' => $info['type'],
            'path' => $info['url'],
            'url' => $info['url'],
            'thumb' => '',
            'ext' => $info['ext'],
            'size' => $info['size'],
            'md5' => $info['md5'],
            'sha1' => $info['sha1'],
            'module' => 'shop',
            'driver' => 'qiniu',
            'create_time' => time(),
            'update_time' => time(),
        ];
        if ($file_add = AttachmentUtil::createAttachment($file_info)) {
            $this->return_app_data(self::SUCCESS_CODE, ['path' => $file_info['path'], 'url' => $file_info['path']]);
        } else {
            $this->return_app_data(self::ERROR_CODE, '没有上传文件');
        }
    }

    public function uploadFileAction()
    {
        $driver = C('PICTURE_UPLOAD_DRIVER');
        $config = [
            'maxSize' => 50 * 1024 * 1024, // 10M 上传的文件大小限制 (0-不做限制)
            //			'exts'     => ['mp4','pdf'], // 允许上传的文件后缀
            'rootPath' => '/file_action/',
        ];
        try {
            if (empty($_FILES['file'])) $this->return_app_data(0, '没有上传文件');// 判断附件是否已存在
            $file_md5 = get_file_hash($_FILES['file']['tmp_name'], 'md5');
            if ($file_exists = AttachmentUtil::getAttachmentInfoByMd5($file_md5)) {
                $this->return_app_data(1, [
                    'path' => $file_exists['path'],
                    'url' => $file_exists['path'],
                ]);
                // 实例化上传类
                $upload = new \Think\Upload($config, C('PICTURE_UPLOAD_DRIVER'), C("UPLOAD_{$driver}_CONFIG"));
                // 上传文件
                $info = $upload->uploadOne($_FILES['file']);
                // 上传错误提示错误信息
                if (!$info) $this->return_app_data(0, $upload->getError());
                $file_info = [
                    'user_id' => 0,
                    'name' => $_FILES['file']['name'],
                    'mime' => $info['type'],
                    'path' => $info['url'],
                    'url' => $info['url'],
                    'thumb' => '',
                    'ext' => $info['ext'],
                    'size' => $info['size'],
                    'md5' => $info['md5'],
                    'sha1' => $info['sha1'],
                    'module' => 'shop',
                    'driver' => 'qiniu',
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                if ($file_add = AttachmentUtil::createAttachment($file_info)) {
                    $this->return_app_data(1, ['path' => $file_info['path'], 'url' => $file_info['path']]);
                } else {
                    $this->return_app_data(0, '没有上传文件');
                }
            }
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            echo '出错了';
        }
    }

    public function uploadLocal()
    {
        header("Access-Control-Allow-Origin:*");
        if ($_FILES["file"]["error"]) {
            $this->return_app_data(0, $_FILES["file"]["error"]);
        } else {
            //判断上传文件类型为png或jpg且大小不超过1024000B
            //防止文件名重复
            $filename = SITE_PATH . 'Data/upload/business_' . md5(time());
            //转码，把utf-8转成gb2312,返回转换后的字符串， 或者在失败时返回 FALSE。
            $filename = iconv("UTF-8", "gb2312", $filename);
            //检查文件或目录是否存在
            if (file_exists($filename)) {
                $this->return_app_data(0, '该文件已存在');
            } else {
                //保存文件,   move_uploaded_file 将上传的文件移动到新位置,
                ////将临时地址移动到指定地址
                if (move_uploaded_file($_FILES["file"]["tmp_name"], $filename)) {
                    $shop_pay_rcode_url = BaseData::uploadStaticFile(md5(time()), $filename, $is_source = false);
                    $this->return_app_data(1, $shop_pay_rcode_url);
                }
            }
        }
    }

    /**
     * 获得上传令牌
     * @return null
     */
    public function getUploadSign(){
        $params = I('get.');
        $postParams = I('post.');
        $params = array_merge($params,$postParams);
        $this->uploadService->setParams([
            'filename' => arr_get($params,'filename'),
            'scene' =>  arr_get($params,'scene'),
        ]);
        return $this->return_app_data(0,$this->uploadService->getUploadSign());
    }
}

?>
